<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="pointQueryForm" :inline="true">
        <el-form-item :label="$t('point.pointName')" prop="id">
          <el-select
              v-model="pointQueryForm.id"
              :placeholder="
              $t('common.placeholderSelect') + $t('point.pointName')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in pointList"
                :key="index"
                :label="locale ? item.pointCnName : item.pointEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="addpoint" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>
          <el-button @click="uploadpoint" type="default" icon="upload">{{
              $t("common.upload")
            }}
          </el-button>
          <el-button @click="classfiyStru" type="default" icon="Filter">{{
              $t("common.classfiyStru")
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="pointForm"
        :form-rules="pointRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item :label="$t('point.pointCnName')" prop="pointCnName">
          <el-input
              v-model="pointForm.pointCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('point.pointCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('point.pointEnName')" prop="pointEnName">
          <el-input
              v-model="pointForm.pointEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('point.pointEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('point.variableType')" prop="variableType">
          <el-input
              v-model="pointForm.variableType"
              :placeholder="
              $t('common.placeholderInput') + $t('point.variableType')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('point.unit')" prop="unit">
          <el-input
              v-model="pointForm.unit"
              :placeholder="
              $t('common.placeholderInput') + $t('point.unit')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('point.address')" prop="address">
          <el-input
              v-model="pointForm.address"
              :placeholder="
              $t('common.placeholderInput') + $t('point.address')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('point.precision')" prop="precision">
          <el-input
              v-model="pointForm.precision"
              :placeholder="
              $t('common.placeholderInput') + $t('point.precision')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          >
            <!-- 场站管理标题 -->
            <div class="station-management-header">
              <div class="title-wrapper">
                <el-icon class="title-icon">
                  <OfficeBuilding/>
                </el-icon>
                <h3 class="station-title">{{$t('point.pointYcManagement')}}</h3>
              </div>
              <div class="station-stats">
                <span class="stat-item">
                  <span class="stat-label">{{$t('point.pointYcNum')}}：</span>
                  <span class="stat-value">{{ total }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">{{$t('point.gatewayAssociated')}}：</span>
                  <span class="stat-value">{{ getgatewayNameBygatewayId(gatewayId) }}</span>
                </span>

              </div>
            </div>
            <!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('point.pointCnName')"
                  align="center"
                  prop="pointCnName"
              />
              <el-table-column
                  :label="$t('point.pointEnName')"
                  align="center"
                  prop="pointEnName"
              />
              <el-table-column
                  :label="$t('point.unit')"
                  align="center"
                  prop="unit"
              />
              <el-table-column
                  :label="$t('point.variableType')"
                  align="center"
                  prop="variableType"
              >
              </el-table-column>
              <el-table-column
                  :label="$t('point.address')"
                  align="center"
                  prop="address"
              >
              </el-table-column>
              <el-table-column
                  :label="$t('point.precision')"
                  align="center"
                  prop="precision"
              >
              </el-table-column>
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="200"
                  fixed="right"
              >
                <template #default="scope">
                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updatepoint(scope.row)"
                  >{{ $t("common.edit") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="deletepoint(scope.row)"
                  >{{ $t("common.delete") }}
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="pointQueryForm.pageNum"
                  v-model:page-size="pointQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 10000]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- CSV文件上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      :title="$t('point.uploadCsv')"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :action="'#'"
        :limit="1"
        :accept="'.csv'"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-exceed="handleExceed"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          {{ $t('common.uploadText') }} <em>{{ $t('common.uploadClick') }}</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            {{ $t('point.uploadCsvTip') }}
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">
            {{ $t('common.cancel') }}
          </el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploadLoading">
            {{ $t('common.upload') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getpointListApi,
  getpointPageApi,
  addpointApi,
  updatepointApi,
  delpointApi,
  uploadPointCsvApi,
} from "@/api/ems/point/pointYc.ts";
import {
  getgatewayListApi,
} from "@/api/ems/gateway/gateway.ts";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {OfficeBuilding, UploadFilled} from "@element-plus/icons-vue";
import {useI18n} from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import {reactive, ref, onMounted, onUnmounted, watch, nextTick} from "vue";
import {useRoute, useRouter} from "vue-router";
const router = useRouter();
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const route = useRoute();
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const {t} = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 场站查询表单数据
const pointQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  id: "", // 设备Id
  gatewayId: null,//场站ID
});
// 2. 场站新增表单数据
const pointForm = reactive({
  pointCnName: "", // 点位中文名称
  pointEnName: "", // 点位英文名称
  unit: null,//点位单位
  gatewayId: null,  // 所属设备ID
  variableType: null,//变量类型
  address: null, //点位地址
  precision: null, //点位精度
});
// 3. 标签表单校验规则
const pointRules = reactive({
  pointCnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  pointEnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  unit: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  variableType: [
    {required: true, message: t("common.placeholderInput"), trigger: "change"},
  ],
  address: [
    {required: true, message: t("common.placeholderInput"), trigger: "change"},
  ],
  precision: [
    {required: true, message: t("common.placeholderInput"), trigger: "change"},
  ],
});
//设备列表
const pointList = ref([]);
//系统单元分类枚举
const sysInfoCategoryEnums = ref([]);
//设备列表
const gatewayList = ref([]);

// CSV上传相关变量
const uploadDialogVisible = ref(false);
const uploadLoading = ref(false);
const uploadRef = ref();
const fileList = ref([]);
const selectedFile = ref(null);
//根据场站ID获取场站名称
const getStationNameByStationId = (id) => {
  stationList.value?.forEach(item => {
    if (item.id == id) {
      return locale ? item.stationCnName : item.stationEnName;
    }
  })
}

//查询
const search = () => {
  getSelectPage();
};
const handleSizeChange = (val) => {
  pointQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  pointQueryForm.pageNum = val;
  getSelectPage();
};
const getSelectPage = () => {
  getpointPageApi(pointQueryForm).then((res) => {
    tableData.value = res.data.records;
    total.value = res.data.total;
  });
};
const getpointList = () => {
  getpointListApi(pointQueryForm).then((res) => {
    pointList.value = res.data;
  });
};

// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addpoint = () => {
  dialogVisible.value = true;
  Object.assign(pointForm, {
    id: null,
    gatewayId: gatewayId.value,  // 设备ID
    pointCnName: "", // 点位中文名称
    pointEnName: "", // 点位英文名称
    unit: null,//点位单位
    variableType: null,//变量类型
    address: null, //点位地址
    precision: null, //点位精度

  });
  dialogTitle.value = t("point.pointAdd");
};
//修改调出弹框
const pointId = ref();
const updatepoint = (row) => {
  dialogTitle.value = t("point.pointUpdate");
  dialogVisible.value = true;
  pointId.value = row.id;
  Object.assign(pointForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};

//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("point.pointAdd")) {
    addpointApi(pointForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  } else {
    updatepointApi(Object.assign(pointForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  }
};
//删除数据
const deletepoint = (row) => {
  ElMessageBox.confirm(
      `是否确认删除`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
  ).then(() => {
    delpointApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};
//获取设备列表
const getgatewayList = () => {
  getgatewayListApi().then((res) => {
    gatewayList.value = res.data;
  });
};
//根据ID获取设备名称
const getgatewayNameBygatewayId = (id) => {
  let res = "";
  gatewayList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.gatewayCnName : item.gatewayEnName;
    }
  })
  return  res
}
//点表结构划分
const classfiyStru = ()=>{
  if(tableData.value.length <= 0){
    ElMessage.warning(t("数据点表为空"));
  }else{
    router.push({
      path: '/stationMangement/pointStru',
      query: {
        gatewayId: gatewayId.value,
        pointSignalType : 0,
        size : tableData.value.length
      }
    })
  }

}
// CSV上传相关函数
const uploadpoint = () => {
  uploadDialogVisible.value = true;
  fileList.value = [];
  selectedFile.value = null;
};

const handleFileChange = (file, files) => {
  selectedFile.value = file.raw;
  fileList.value = files;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning('只能上传一个文件，请先删除已选择的文件');
};

const submitUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择CSV文件');
    return;
  }

  // 验证文件类型
  const fileExtension = selectedFile.value.name.split('.').pop().toLowerCase();
  if (fileExtension !== 'csv') {
    ElMessage.error('只能上传CSV文件');
    return;
  }

  uploadLoading.value = true;

  try {
    const response = await uploadPointCsvApi(selectedFile.value, gatewayId.value);

    if (response.code === 200) {
      ElMessage.success('CSV文件上传成功，数据正在处理中');
      uploadDialogVisible.value = false;
      // 刷新数据
      getSelectPage();
    } else {
      ElMessage.error(response.msg || 'CSV文件上传失败');
    }
  } catch (error) {
    console.error('CSV上传错误:', error);
    ElMessage.error('CSV文件上传失败：' + (error.message || '未知错误'));
  } finally {
    uploadLoading.value = false;
  }
};

//场站ID（路由跳转的参数ID）
const gatewayId = ref();
onMounted(() => {
  gatewayId.value = route.query.gatewayId;
  pointQueryForm.gatewayId = gatewayId.value;

  pointForm.gatewayId = gatewayId.value;
  getSelectPage();
  getpointList();
  getgatewayList();
});
onUnmounted(() => {
});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}

.app-container {
  .station-management-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .title-wrapper {
      display: flex;
      align-items: center;
      gap: 12px;

      .title-icon {
        font-size: 24px;
        color: #ffffff;
      }

      .station-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #ffffff;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .station-stats {
      display: flex;
      gap: 24px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 12px;
        background: rgba(255, 255, 255, 0.15);
        border-radius: 20px;
        backdrop-filter: blur(10px);

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }

        .stat-value {
          font-size: 16px;
          font-weight: 600;
          color: #ffffff;
        }
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .station-management-header {
      flex-direction: column;
      gap: 16px;
      text-align: center;

      .station-stats {
        justify-content: center;
      }
    }
  }
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
